﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ghasam.Business.Services;
using Ghasam.Business.Domain.Entity;
using Mani.Common;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public partial class InternalAccountingPage : System.Web.UI.Page
{
    private IInternalAccountingService internalAccountingService;
    private ISalesPersonService salesPersonService;
    InternalAccounting example = new InternalAccounting();
    DateTime? StartDate = null;
    DateTime? EndDate = null;
    public ISalesPersonService SalesPersonService {
        get { return salesPersonService; }
        set { salesPersonService = value; }
    }

    public IInternalAccountingService InternalAccountingService
    {
        get { return internalAccountingService; }
        set { internalAccountingService = value; }
    }
    static int numberDiv = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        CheckHidden();
        if (!Page.IsPostBack)
        {
            GetAccounts();
            GetInternalAccountings(0, true);
        }
    }

    private void CheckHidden() {
        bool show = CommonHelper.ShowHiddenCustomers();

        drpAccountingType.Visible = show;
        lblAccountingType.Visible = show;
        gvInternalAccountings.Columns[1].Visible = show;
        trInternalAccountingType.Visible = show;
    }

    private void GetAccounts() {
        ddlAccounts.DataSource = internalAccountingService.GetAccounts();
        ddlAccounts.DataTextField = "Name";
        ddlAccounts.DataValueField = "Id";
        ddlAccounts.DataBind();

        ddlAccount.DataSource = internalAccountingService.GetAccounts();
        ddlAccount.DataTextField = "Name";
        ddlAccount.DataValueField = "Id";
        ddlAccount.DataBind();
    }

    private void GetValues()
    {
        if (!String.IsNullOrEmpty(txtInvoiceNumber.Text))
            example.InvoiceNumber = Convert.ToInt64(txtInvoiceNumber.Text);

        if (ddlAccounts.SelectedValue != "-1")
            example.Account = internalAccountingService.GetAccount(Convert.ToInt32(ddlAccounts.SelectedValue));

        if (!String.IsNullOrEmpty(txtSalesPerson.Text))
            example.SalesPerson = salesPersonService.FindByTitle(txtSalesPerson.Text);

        if (!String.IsNullOrEmpty(txtStartDate.Text))
            StartDate = MyPersianDate.PersianToDateTime(txtStartDate.Text);

        if (!String.IsNullOrEmpty(txtEndDate.Text))
            EndDate = MyPersianDate.PersianToDateTime(txtEndDate.Text);

        example.AccountingType = internalAccountingService.GetInternalAccountingType(Convert.ToInt32(drpAccountingType.SelectedValue));
    }

    private void GetInternalAccountings(int pageNumber, bool setPageCount)
    {
        GetValues();
        if (setPageCount) {
            gvInternalAccountings.VirtualItemCount = internalAccountingService.CountFind( example, StartDate, EndDate);
        }
        gvInternalAccountings.DataSource = internalAccountingService.Find(15, pageNumber, example, StartDate, EndDate);
        gvInternalAccountings.DataBind();
    }

    protected void gvInternalAccountings_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvInternalAccountings.PageIndex = e.NewPageIndex;
        GetInternalAccountings(e.NewPageIndex, false);
    }

    protected void gvInternalAccountings_RowDeleting(object sender, GridViewDeleteEventArgs e) {
        int Id = Convert.ToInt32(gvInternalAccountings.DataKeys[e.RowIndex].Value);
        internalAccountingService.DeleteInternalAccounting(Id);
        GetInternalAccountings(0, true);
    }

    protected void btnSearch_Click(object sender, EventArgs e) {
        if (!Page.IsValid) {
            btnSearch.Focus();
            return;
        }

        GetInternalAccountings(0, true);
    }

    protected void gvInternalAccountings_SelectedIndexChanged(object sender, EventArgs e)
    {
        resetEditForm();

        int id = Convert.ToInt32(gvInternalAccountings.DataKeys[gvInternalAccountings.SelectedIndex].Value);
        InternalAccounting i = internalAccountingService.GetInternalAccounting(id);
        tbEdit.Visible = true;

        if ( i.Account != null )
            ddlAccount.Items.FindByValue(i.Account.Id.ToString()).Selected = true;
        
        txtAccountingDate.Text = MyPersianDate.DateTimeToPersian(i.AccountingDate);

        if (i.SalesPerson != null)
            txtSalesPersonEdit.Text = i.SalesPerson.Title;

        if (i.Item != null)
            txtItemName.Text = i.Item.Name;

        txtQuantity.Text = (i.Quantity == null ) ? "" : i.Quantity.ToString();
        txtUnitPrice.Text = (i.UnitPrice == null ) ? "" : i.UnitPrice.ToString();
        txtInvoiceNo.Text = i.InvoiceNumber.ToString();
        cbPaid.Checked = i.Paid.Value;
        txtDiscount.Text = (i.Credit == null) ? "" : i.Credit.ToString();
        ddlInternalAccountingType.Items.FindByValue(i.AccountingType.Id.ToString()).Selected = true;
        txtDesc.Text = i.Description;
        btnUpdateInternalAccounting.Focus();
    }

    protected void gvInternalAccountings_Sorting(object sender, GridViewSortEventArgs e)
    {
        bool dir;
        if ((numberDiv % 2) == 0)
            dir = true;
        else
            dir = false;
        numberDiv++;
        GetValues();
        gvInternalAccountings.DataSource = internalAccountingService.SortInternalAccounting(15, 0, example, StartDate, EndDate,e.SortExpression,dir);
        gvInternalAccountings.DataBind();
    }

    protected void btnUpdateInternalAccounting_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid) {
            btnUpdateInternalAccounting.Focus();
            return;
        }

        if (txtDiscount.Text != String.Empty && txtDiscount.Text != "0" && !String.IsNullOrEmpty(txtItemName.Text)) {
            UIHelper.ClientAlert(this, "نوع حساب داخلی باید یا از نوع تخفیف باشد یا هزینه لطفا تنها یکی از موارد را پر کنید");
            return;
        }

        SalesPerson salesPerson = null;
        if (!String.IsNullOrEmpty(txtSalesPersonEdit.Text)) {
            salesPerson = salesPersonService.FindByTitle(txtSalesPersonEdit.Text);
            if ( salesPerson == null ){
                UIHelper.ClientAlert(this, "فروشنده در لیست فروشندگان یافت نشد");
                return;
            }
        }

        Item item = null;
        if (!String.IsNullOrEmpty(txtItemName.Text)) {
            item = InternalAccountingService.FindItemByName(txtItemName.Text);
            if (item == null) {
                UIHelper.ClientAlert(this, "کالا در لیست کالاهای موجود یافت نشد");
                return;
            }
        }

        int id = Convert.ToInt32(gvInternalAccountings.DataKeys[gvInternalAccountings.SelectedIndex].Value);

        InternalAccounting oldI = internalAccountingService.GetInternalAccounting(id);
        InternalAccounting newI = new InternalAccounting();
      
        if ( ddlAccount.SelectedValue != "-1" )
            newI.Account = internalAccountingService.GetAccount(Convert.ToInt32(ddlAccount.SelectedValue));

        newI.AccountingDate = MyPersianDate.PersianToDateTime(txtAccountingDate.Text);
        newI.AccountingType = internalAccountingService.GetInternalAccountingType(Convert.ToInt32(ddlInternalAccountingType.SelectedValue));
        newI.Description = txtDesc.Text;
        newI.InvoiceNumber = Convert.ToInt64(txtInvoiceNo.Text);

        if (item != null) {
            newI.Item = item;
            newI.Quantity = Convert.ToSingle(txtQuantity.Text);
            newI.UnitPrice = Convert.ToSingle(txtUnitPrice.Text);
            Single quantity = Convert.ToSingle(txtQuantity.Text);
            Single unitPrice = Convert.ToSingle(txtUnitPrice.Text);
            newI.Debit = (quantity * unitPrice);
            newI.Credit = 0;
        }
        else {
            newI.Credit = Convert.ToSingle(txtDiscount.Text);
            newI.Debit = 0;
        }

        newI.ModifyStamp = DateTime.Now;
        newI.Paid = cbPaid.Checked;

        if (salesPerson != null)
            newI.SalesPerson = salesPerson;

        internalAccountingService.NewInternalAccounting(newI);
        internalAccountingService.DeleteInternalAccounting(oldI);
        GetInternalAccountings(0, true);
        gvInternalAccountings.SelectedIndex = -1;
        tbEdit.Visible = false;
        resetEditForm();
    }

    private void resetEditForm() {
        txtAccountingDate.Text = String.Empty;
        ddlAccount.SelectedIndex = -1;
        txtSalesPersonEdit.Text = "";
        txtItemName.Text = "";
        txtQuantity.Text = String.Empty;
        txtUnitPrice.Text = String.Empty;
        txtDiscount.Text = String.Empty;
        txtInvoiceNo.Text = String.Empty;
        cbPaid.Checked = false;
        txtDesc.Text = String.Empty;
    }
}
